package com.ktjy.actual.actual01;

import java.lang.reflect.Proxy;

public class LogTest {
    public static void main(String[] args) {
        //创建原始对象
        LogService logService = new LogServiceImpl();
        LoggingInvocationHandler loggingInvocationHandler = new LoggingInvocationHandler(logService); //创建代理对象
        //创建代理对象
        LogService proxyInstance=(LogService) Proxy.newProxyInstance(
                logService.getClass().getClassLoader(), //确保代理类和目标类在同一个类加载器环境中
                logService.getClass().getInterfaces(),  //获取目标对象实现的所有接口
                loggingInvocationHandler
        );

        proxyInstance.testMethod1();
        proxyInstance.testMethod2();
        proxyInstance.testMethod3();
    }

    interface LogService{
        void testMethod1();
        void testMethod2();
        void testMethod3();
    }

    static class LogServiceImpl implements LogService{

        @Log
        public void testMethod1() {
            try{
                Thread.sleep(1000); //模拟耗时
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        @Log
        public void testMethod2() {
            try{
                Thread.sleep(100); //模拟耗时
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void testMethod3() {
            try{
                Thread.sleep(1000); //模拟耗时
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
